<template>
  <cu-layout title="商品列表">
    <template #navbarExtend>
      <view class="shadow-b">
        <view class="h-44 px-10 flex-ca">
          <u-search :focus="state.focus" v-model="state.keyword" :action-style="{color: $u.color.primary}" animation height="30" placeholder="商品名称" />
        </view>
        <view class="tabs h-42 leading-22 flex-a hair-t">
          <view class="flex-1 flex-ca" @click="state.cateShow = true">
            <view class="px-6">
              <text v-if="state.cateId" class="active">{{ cateLabel }}</text>
              <text v-else class="">全部分类</text>
            </view>
            <view class="">
              <view class="iconfont icon-shaixuan text-14" :class="cateLabel ? 'active' : ''" />
            </view>
          </view>
          <view class="flex-1 flex-ca hair-x" @click="onSort('price')">
            <view class="px-6" :class="state.field === 'price' ? 'active' : ''">价格</view>
            <view class="">
              <view :class="state.field === 'price' && state.sort === 'asc' ? 'active' : ''" class="iconfont icon-xiangshang1" />
              <view :class="state.field === 'price' && state.sort === 'desc' ? 'active' : ''" class="iconfont icon-xiangxia1" />
            </view>
          </view>
          <view class="flex-1 flex-ca" @click="onSort('num')">
            <view class="px-6" :class="state.field === 'num' ? 'active' : ''">销量</view>
            <view class="">
              <view :class="state.field === 'num' && state.sort === 'asc' ? 'active' : ''" class="iconfont icon-xiangshang1" />
              <view :class="state.field === 'num' && state.sort === 'desc' ? 'active' : ''" class="iconfont icon-xiangxia1" />
            </view>
          </view>
        </view>
      </view>
    </template>
    <cu-goods-list :list="usePage.list" />
    <u-loadmore :status="usePage.status" />
    <u-picker ref="catePickerRef" key-name="name" :show="state.cateShow" :columns="state.cateColumns" @confirm="cateConfirm" @change="cateChange" />
  </cu-layout>
</template>

<script setup>
import { computed, ref, reactive } from 'vue'
import { onLoad, onReachBottom } from '@dcloudio/uni-app'
import $ from '@/sheep'

const searchRef = ref(null)

const state = reactive({
  keyword: '',
  cateId: 0,
  cateAll: [],
  cateList: [],
  cateShow: false,
  cateColumnsAll: [],
  cateColumns: [],
  sort: '',
  field: '',
	focus: false
})
const { form: usePage } = $.useForm({
  page: 1,
  list: [],
  limit: 20,
  status: 'loadmore' // loading / nomore
})
const catePickerRef = ref(null)
const cateLabel = computed(() => {
  return state.cateId && state.cateAll.find(v => v.id === state.cateId)?.name || ''
})
onLoad(async(options) => {
  if (options.cateId) {
		state.cateId = Number(options.cateId)
	} else {
		state.focus = true
	}
  state.cateAll = await $.utils.getList('store/category')
  state.cateList = $.utils.toTree(state.cateAll)

  let topNode = { id: 0, name: '全部分类', pid: 0, children: [] }
  state.cateColumnsAll = [topNode, ...state.cateList].map(v => {
    v.children.unshift({ id: v.id, name: v.name })
    return v
  })
  const nodes = $.utils.findTreeParents(state.cateColumnsAll, state.cateId)
  if (nodes) {
    state.cateColumns = [state.cateColumnsAll, state.cateColumnsAll[nodes[0].index].children]
    const defaultIndex = [nodes[0].index, nodes[1]?.index ?? 0]
    catePickerRef.value.setIndexs(defaultIndex, defaultIndex)
  }
  reload()
})
onReachBottom(() => {
  if (usePage.status === 'loadmore') {
    usePage.page += 1
    reload()
  }
})

function reload() {
  if (usePage.status !== 'loadmore') return
  usePage.status = 'loading'
  $.utils.get('/Store/products', {
    cate_id: state.cateId,
    keyword: state.keyword,
    sort: state.sort,
    field: state.field,
    page: usePage.page,
    limit: usePage.limit
  }, { isShop: true }).then(res => {
    const data = res.data.map(v => {
      v.price = v.retail_price.toString().split('.')
      return v
    })
    if (usePage.page > 1) {
      usePage.list.push(...data)
    } else {
      usePage.list = data
    }
    usePage.status = usePage.limit > data.length ? 'nomore' : 'loadmore'
  })
}

function onSort(field) {
  if (state.field === field) {
    if (state.sort === 'desc') {
      state.sort = 'asc'
    } else {
      state.sort = ''
      state.field = ''
    }
  } else {
    state.field = field
    state.sort = 'desc'
  }
}

function cateConfirm(e) {
  state.cateId = e.value[1].id
  state.cateShow = false
}

function cateChange(e) {
  if (e.columnIndex === 0) {
    catePickerRef.value.setColumnValues(1, state.cateColumnsAll[e.index].children)
  }
}

</script>
<style lang="scss">
.tabs {
	.iconfont {
		color: $u-tips-color;
	}
	.icon-shaixuan {
		font-size: 28rpx;
	}
	.icon-xiangshang1, .icon-xiangxia1 {
		line-height: 14rpx;
		font-size: 18rpx;
	}
	.active {
		color: $u-primary;
	}
}

</style>
